package com.example.myapplication.ui.home;

import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.myapplication.R;
import com.example.myapplication.databinding.HomeFragmentBinding;
import com.example.myapplication.pojo.Article;
import com.example.myapplication.pojo.SingleUser;
import com.example.myapplication.ui.login.MainActivity;
import com.example.myapplication.ui.self.SelfActivity;
import com.example.myapplication.ui.wr.WrActivity;
import com.example.myapplication.utils.MySqliteHelper;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 *
 */
public class HomeFragment extends Fragment {

    private HomeViewModel mViewModel;
    private HomeFragmentBinding binding;
    private HomeRecyclerViewAdapter adapter;
    private String TAG = "HomeFragment";
    List<Article> list = new ArrayList<>();

    public static HomeFragment newInstance() {
        return new HomeFragment();
    }

    /**
     * 初始化 注册数据
     *
     * @param inflater
     * @param container
     * @param savedInstanceState
     * @return
     */
    @Nullable
    @Override
    public View onCreateView(@NonNull final LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {


        mViewModel = new ViewModelProvider(this).get(HomeViewModel.class);
        binding = DataBindingUtil.inflate(inflater, R.layout.home_fragment, container, false);
        binding.setData(mViewModel);

        binding.toolbar2.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getActivity().finish();
            }
        });

        find();

        if (!list.isEmpty()) {
            adapter = new HomeRecyclerViewAdapter(getContext(), list);
            adapter.setViewClickListenser(new HomeRecyclerViewAdapter.ViewClickListenser() {
                /**
                 * 删除的第一个问题
                 * @param view
                 * @param id
                 * @param position
                 */
                @Override
                public void onDelete(View view, int id, int position) {
                    Log.d(TAG, "onDelete: " + id);
                    // 删除 数据库
                    delete(id);
                    list.remove(position);
                    adapter.notifyDataSetChanged();
                }

                @Override
                public void onModify(View view, int id) {
                    Log.d(TAG, "onModify: " + id);
                    Intent intent = new Intent(getContext(), WrActivity.class);
                    intent.putExtra("choose", 2);
                    Bundle bundle = new Bundle();
                    bundle.putInt("choose", 2);
                    bundle.putInt("id", id);
                    bundle.putInt("all", list.size());
                    intent.putExtras(bundle);
                    startActivity(intent);
                }

            });
            binding.recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
            binding.recyclerView.setAdapter(adapter);
        }

        // 新建文档
        binding.wen.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getContext(), WrActivity.class);
                Bundle bundle = new Bundle();
                bundle.putInt("choose", 1);
                intent.putExtras(bundle);
                startActivity(intent);
            }
        });

        // 个人中心
        binding.geren.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getContext(), SelfActivity.class);
                startActivity(intent);
            }
        });
        return binding.getRoot();

    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        list.clear();

        find();

        adapter.notifyDataSetChanged();
    }

    public void find() {
        MySqliteHelper mySqliteHelper = new MySqliteHelper(getContext());
        SQLiteDatabase readableDatabase = mySqliteHelper.getReadableDatabase();
        //查找当前哟用户所有的文章
        Cursor cursor = readableDatabase.query("article", new String[]{"id", "date", "name", "information"}, "name=?", new String[]{SingleUser.getInstance().getUser().getName()}, null, null, null);
        if (cursor.getCount() > 0) {
            while (cursor.moveToNext()) {
                Article article = new Article();
                article.setId(cursor.getInt(cursor.getColumnIndex("id")));
//                SimpleDateFormat formatter= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                article.setDate(new Date(cursor.getString(cursor.getColumnIndex("date"))));
                article.setName(cursor.getString(cursor.getColumnIndex("name")));
                article.setInformation(cursor.getString(cursor.getColumnIndex("information")));
                list.add(article);
            }
            Log.d(TAG, list.toString());
        } else {
            Toast.makeText(getContext(), "对不起你没有写任何 一篇文章", Toast.LENGTH_SHORT).show();
        }
        cursor.close();
        readableDatabase.close();
    }

    public void delete(int id) {
        MySqliteHelper mySqliteHelper = new MySqliteHelper(getActivity());
        SQLiteDatabase db = mySqliteHelper.getReadableDatabase();
        int i = db.delete("article", "id= ?", new String[]{String.valueOf(id)});
        if (i > 0) {
            Toast.makeText(getActivity(), "删除成功", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(getActivity(), "删除失败", Toast.LENGTH_SHORT).show();
        }
        db.close();
    }
}